import { useEffect, useRef, useState } from 'react'

export default function useCountDown (initCount = 10, callBack = () => {}) {
  const timeId = useRef({ id: -1 })
  //   const timeId = useRef<number>(null)

  const [count, setCount] = useState(initCount)

  const start = () => {
    setCount(initCount)
    timeId.current.id = window.setInterval(() => {
      setCount((count) => count - 1)
    }, 1000)
  }
  useEffect(() => {
    return () => {
      console.log('..........')
      window.clearInterval(timeId.current.id)
    }
  }, [])

  useEffect(
    () => {
      console.log(count, timeId.current)
      if (count === 0) {
        window.clearInterval(timeId.current.id)
        callBack()
      }
    },
    [count]
  )

  return { count, start }
}
